using Microsoft.Maui.Controls;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using MauiApp.Views;
using MauiApp.Models;
using MauiApp.Services;

namespace MauiApp.ViewModels
{
    public class LoginViewModel : INotifyPropertyChanged
    {
        // 服务实例
        private readonly IApiService _apiService;
        
        // 页面引用
        public LoginPage LoginPage { get; set; }
        
        // 加载状态
        private bool _isLoading;
        public bool IsLoading
        {
            get => _isLoading;
            set
            {
                _isLoading = value;
                OnPropertyChanged();
            }
        }
        
        // 错误信息
        private string _errorMessage;
        public string ErrorMessage
        {
            get => _errorMessage;
            set
            {
                _errorMessage = value;
                OnPropertyChanged();
                ShowErrorMessage = !string.IsNullOrEmpty(value);
            }
        }
        
        // 错误信息是否可见
        private bool _showErrorMessage;
        public bool ShowErrorMessage
        {
            get => _showErrorMessage;
            set
            {
                _showErrorMessage = value;
                OnPropertyChanged();
            }
        }
        
        // 登录命令
        public ICommand LoginCommand { get; }
        
        // 构造函数
        public LoginViewModel()
        {
            // 获取服务实例
            _apiService = App.ServiceProvider.GetRequiredService<IApiService>();
            
            // 初始化命令
            LoginCommand = new Command<object>(async (obj) => await ExecuteLoginCommandAsync());
            
            LogHelper.Debug("LoginViewModel: 已初始化");
        }
        
        // 执行登录命令
        private async Task ExecuteLoginCommandAsync()
        {
            // 重置错误信息
            ErrorMessage = string.Empty;
            
            // 获取用户名和密码
            string username = LoginPage?.GetUsername() ?? string.Empty;
            string password = LoginPage?.GetPassword() ?? string.Empty;
            
            // 简单验证
            if (string.IsNullOrWhiteSpace(username))
            {
                ErrorMessage = "请输入用户名";
                return;
            }
            
            if (string.IsNullOrWhiteSpace(password))
            {
                ErrorMessage = "请输入密码";
                return;
            }
            
            // 设置加载状态
            IsLoading = true;
            LoginPage?.SetLoadingState(true);
            
            try
            {
                // 调用登录API
                var response = await _apiService.LoginAsync(new LoginRequest
                {
                    Username = username,
                    Password = password
                });
                
                if (response != null && response.Success)
                {
                    LogHelper.Info("LoginViewModel: 登录成功");
                    
                    // 更新静态全局用户信息
                    App.CurrentUsername = username;
                    // 使用ApiService中正确的用户ID
                    if (_apiService is ApiService apiService)
                    {
                        string userId = apiService.GetCurrentUserId();
                        App.CurrentUserId = userId;
                    }
                    else
                    {
                        App.CurrentUserId = username; // 回退方案
                    }
                    App.LogCurrentUserInfo("LoginViewModel.ExecuteLoginCommandAsync");
                    
                    // 登录成功，导航到主页面
                    await LoginPage?.NavigateToMainPageAsync();
                }
                else
                {
                    // 登录失败，显示错误信息
                    ErrorMessage = response?.Message ?? "登录失败，请重试";
                    LogHelper.Warn($"LoginViewModel: 登录失败: {ErrorMessage}");
                }
            }
            catch (Exception ex)
            {
                // 处理异常
                ErrorMessage = "登录过程中发生错误，请检查网络连接";
                LogHelper.Error($"LoginViewModel: 登录异常: {ex.Message}");
            }
            finally
            {
                // 重置加载状态
                IsLoading = false;
                LoginPage?.SetLoadingState(false);
            }
        }
        
        // 尝试自动登录
        public async Task TryAutoLoginAsync()
        {
            try
            {
                LogHelper.Debug("LoginViewModel: 尝试自动登录");
                
                // 调用ApiService的自动登录方法
                bool success = await ((ApiService)_apiService).TryAutoLoginAsync();
                
                if (success)
                {
                    LogHelper.Info("LoginViewModel: 自动登录成功");
                    
                    // 获取当前用户名和用户ID并更新静态全局用户信息
                    ApiService apiService = (ApiService)_apiService;
                    string currentUsername = apiService.GetCurrentUsername();
                    string currentUserId = apiService.GetCurrentUserId();
                    App.CurrentUsername = currentUsername;
                    App.CurrentUserId = currentUserId;
                    LogHelper.Debug($"LoginViewModel: 自动登录后更新静态全局用户信息 - Username: {currentUsername}, UserId: {currentUserId}");
                    
                    // 自动登录成功，导航到主页面
                    await LoginPage?.NavigateToMainPageAsync();
                }
                else
                {
                    LogHelper.Warn("LoginViewModel: 自动登录失败，需要手动登录");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error($"LoginViewModel: 自动登录异常: {ex.Message}");
            }
        }
        
        // INotifyPropertyChanged接口实现
        public event PropertyChangedEventHandler PropertyChanged;
        
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}